//
//  MyDocument.m
//  RollingInTasks
//
//  Created by Rua Haszard Morris on 16/01/10.
//  Copyright __MyCompanyName__ 2010 . All rights reserved.
//

#import "MyDocument.h"

@implementation LimityArrayController

@synthesize limit;

- (BOOL)fetchWithRequest:(NSFetchRequest *)fetchRequest merge:(BOOL)merge error:(NSError **)error
{
//	static int mlimit = 0; //[self limit];
//	mlimit++;
//	if (mlimit == 4)
//		mlimit = 0;
//	[fetchRequest setFetchLimit:mlimit];
	[fetchRequest setFetchLimit:[self limit]];
	return [super fetchWithRequest:fetchRequest merge:merge error:error];
}

@end

@implementation MyDocument

@synthesize tasksFilterPredicate;

- (id)init 
{
    self = [super init];
    if (self != nil) {
        // initialization code
    }
    return self;
}

- (NSString *)windowNibName 
{
    return @"MyDocument";
}

//- (void)windowControllerDidLoadNib:(NSWindowController *)windowController 
//{
//    [super windowControllerDidLoadNib:windowController];
//
////	[self listRegularityPopupSelectionChanged:nil];
//}

-(void)awakeFromNib
{
   [todoListTasksTableView setTarget:self];
   [todoListTasksTableView setDoubleAction:@selector(taskRowDoubleClicked:)];
   
   // some refreshies to set initial state
	[self performSelector:@selector(refreshEverything:) withObject:nil afterDelay:0.0];
	[self performSelector:@selector(showCompletedClicked:) withObject:nil afterDelay:0.0];
}

-(IBAction)jobCountChanged:(id)sender
{
   int count = [jobCountStepper intValue];
   if (count > 0)
      [jobCountLabel setStringValue:[jobCountStepper stringValue]];
   else
      [jobCountLabel setStringValue:@"All"];
    
	[self refreshEverything:nil];
}

-(IBAction)priorityChanged:(id)sender
{
	[priorityLabel setStringValue:[priorityStepper stringValue]];
	[self refreshEverything:nil];
}

-(IBAction)taskCompletedClicked:(id)sender
{
   // This sets the completed date when the user clicks the edit pane checkbox - not the one in the table view.
   // Could key-value observe the completed property to make this more robust, but it is a nicety..
   if ([completedTickBox state] == NSOnState)
      [[taskEditPaneTasksArrayController selectedObjects] setValue:[NSDate date] forKey:@"completionDate"];
}

-(IBAction)taskRowDoubleClicked:(id)sender
{
   int row = [todoListTasksTableView selectedRow];
   id selectedRowObj = [[todoListDataArrayController arrangedObjects] objectAtIndex:row];
   [taskEditPaneTasksArrayController setSelectedObjects:[NSArray arrayWithObjects:selectedRowObj, nil]];
   
   [tabView selectTabViewItem:taskEditTab];
}

-(IBAction)refreshEverything:(id)sender
{
	[self listRegularityPopupSelectionChanged:nil];
}

-(int)regularityTagToDayCount:(int)tag
{
   int days = 8;
   switch (tag) {
      case 1:
         days = 8; // longish week 
         break;
      case 2:
         days = 40; // month ish
         break;
      case 3:
         days = 365; // wo, a whole year
         break;
   }
   return days;
}

-(NSTimeInterval)timeOffsetForDayCount:(int)days
{
   NSTimeInterval aDay =
   60 // seconds
   * 60 // minutes
    * 24; // hours
    
    return aDay * -days; // negative, we wanna go backwards
}

-(IBAction)listRegularityPopupSelectionChanged:(id)sender
{
   int specifiedRegularity = [[regularityPopup selectedItem] tag];
   int specifiedPriority = [priorityStepper intValue];//

   // filter the displayed tasks so that more-regular stuff is temporarily hidden
   NSPredicate* lessThanWeekly = [NSPredicate predicateWithFormat:@"category.regularity == %@", [NSNumber numberWithInt:specifiedRegularity]];
   NSPredicate* atLeastPriorityN = [NSPredicate predicateWithFormat:@"priority <= %@", [NSNumber numberWithInt:specifiedPriority]];
   NSPredicate* jobsForThisWeekInSpecifiedPriority = [NSCompoundPredicate andPredicateWithSubpredicates:
      [NSArray arrayWithObjects:lessThanWeekly, atLeastPriorityN, nil]
   ];
   // add in immediate (ASAP) priority (==1) tasks as well
   NSPredicate* immediatePriority = [NSPredicate predicateWithFormat:@"priority == %@", [NSNumber numberWithInt:1]];
   [todoListDataArrayController setFilterPredicate:[NSCompoundPredicate orPredicateWithSubpredicates:
      [NSArray arrayWithObjects:jobsForThisWeekInSpecifiedPriority, immediatePriority, nil]]
   ];	
   [todoListDataArrayController fetch:nil];

   // filter the displayed categories to match the cur regularity
   NSPredicate* isWeekly = [NSPredicate predicateWithFormat:@"regularity == %@", [NSNumber numberWithInt:specifiedRegularity]];
//   NSPredicate* withinLastPeriod = [NSPredicate predicateWithFormat:@"completionDate >= %@", 
//      [NSDate dateWithTimeIntervalSinceNow:
//         [self timeOffsetForDayCount:[self regularityTagToDayCount:specifiedRegularity]]
//      ]
//   ];
//   [todoListCategoriesDataArrayController setFilterPredicate:[NSCompoundPredicate andPredicateWithSubpredicates:
//      [NSArray arrayWithObjects:isWeekly, withinLastPeriod, nil]]
//   ];
   [todoListCategoriesDataArrayController setFilterPredicate:isWeekly];
   NSSortDescriptor* sortByCatPriority = [NSSortDescriptor sortDescriptorWithKey:@"groupPriority" ascending:YES];
   
   [todoListCategoriesDataArrayController setSortDescriptors:[NSArray arrayWithObjects:sortByCatPriority, nil]];
   [todoListCategoriesDataArrayController fetch:nil];

   [todoListTasksTableView reloadData];
   [todoListCategoriesTableView reloadData];
   //    [self managedObjectContext ]
}

-(IBAction)showCompletedClicked:(id)sender
{
   NSPredicate* completedness = [NSPredicate predicateWithFormat:@"completed == %@", [NSNumber numberWithBool:([showCompletedTickBox state] == NSOnState)]];
   NSPredicate* userTextFilter = tasksFilterPredicate;
   NSPredicate* combinedPredicate = completedness;
   
   if (userTextFilter)
      combinedPredicate = [NSCompoundPredicate andPredicateWithSubpredicates:
         [NSArray arrayWithObjects:userTextFilter, completedness, nil]
      ];   
   
   [taskEditPaneTasksArrayController setFilterPredicate:combinedPredicate];
}

- (int)numberOfRowsInTableView:(NSTableView *)aTableView
{
   int rowCount = 0;
   if (todoListCategoriesTableView == aTableView)
   {
      rowCount = [[todoListCategoriesDataArrayController arrangedObjects] count];
   }
   return rowCount;
}

- (id)tableView:(NSTableView *)aTableView
    objectValueForTableColumn:(NSTableColumn *)aTableColumn
    row:(int)rowIndex
{
   id arrangedRow = [[todoListCategoriesDataArrayController arrangedObjects] objectAtIndex:rowIndex];
   
   id obj = @"";
   if (aTableColumn == categoryTitleColumn)
      obj = [arrangedRow valueForKey:@"title"];
   else if (aTableColumn == categoryTotalColumn)
      obj = [NSNumber numberWithInt:[self calcTotalForCategory:[arrangedRow valueForKey:@"tasks"]]];

   return obj;
}

-(int)calcTotalForCategory:(id)set
{
   int specifiedRegularity = [[regularityPopup selectedItem] tag];
   NSArray* completedArray = nil;
   if ([set respondsToSelector:@selector(allObjects)]); // likely to be a ... NSThingThatImplements allObjects
      completedArray = [set allObjects];
   
   NSDate* minInterestingDate = [NSDate dateWithTimeIntervalSinceNow:[self timeOffsetForDayCount:[self regularityTagToDayCount:specifiedRegularity]]];

   int total = 0;
   for (int i=0; i<[completedArray count]; i++)
   {
      id item = [[completedArray objectAtIndex:i] valueForKey:@"completed"];
      id itemCompletionDate = [[completedArray objectAtIndex:i] valueForKey:@"completionDate"];
      
      if ([itemCompletionDate isKindOfClass:[NSDate class]])
      {   
         NSDate* completedAt = (NSDate*)itemCompletionDate;
         if ([item respondsToSelector:@selector(intValue)] && ([completedAt compare:minInterestingDate] == NSOrderedDescending))
            total += [item intValue];         
      }
   }
   return total;
}

//-(NSArray *)groupTotalsSortDescriptor 
//{
//	return [NSArray arrayWithObject:[[[NSSortDescriptor alloc] initWithKey:@"groupPriority" ascending:YES] autorelease]];
//}

- (BOOL)configurePersistentStoreCoordinatorForURL:(NSURL *)url ofType:(NSString *)fileType modelConfiguration:(NSString *)configuration storeOptions:(NSDictionary *)storeOptions error:(NSError **)error
{
	NSMutableDictionary *newOptions;
 
	if( storeOptions )
	{
		newOptions = [storeOptions mutableCopy];
	}
	else
	{
		newOptions = [[NSMutableDictionary alloc] init];
	}
 
	[newOptions setObject:[NSNumber numberWithBool:YES] forKey:NSMigratePersistentStoresAutomaticallyOption];
 
	BOOL result = [super configurePersistentStoreCoordinatorForURL:url ofType:fileType modelConfiguration:configuration storeOptions:newOptions error:error];
 
	[newOptions release];
	return result;
}

- (BOOL)control:(NSControl*)control textView:(NSTextView*)textView doCommandBySelector:(SEL)commandSelector
{
    BOOL result = NO;

   // hacky override, should be using NSTextView, but anyway..
   // http://developer.apple.com/mac/library/qa/qa2006/qa1454.html
   // enter/return to insert newline, tab to finish editing

    if (commandSelector == @selector(insertNewline:))
    {
        // new line action:
        // always insert a line-break character and don’t cause the receiver to end editing
        [textView insertNewlineIgnoringFieldEditor:self];
        result = YES;
    }
//    else if (commandSelector == @selector(insertTab:))
//    {
//        // tab action:
//        // always insert a tab character and don’t cause the receiver to end editing
//        [textView insertTabIgnoringFieldEditor:self];
//        result = YES;
//    }

    return result;
}

@end
